<template>
    <ph-flex dir="col">
        <ul class="ph-tree">
            <template v-for="(node , index) in trees" :key="index">
                <child-tree 
                :is-root="false" 
                :return-pid="returnPid"
                :ref="'leaf_'+node.id" 
                :node="node" 
                :checkable="checkable" 
                :values="vs"
                />
            </template>
        </ul>
    </ph-flex>
</template>
<script lang="ts">
import { defineComponent,computed, provide } from 'vue'
import {makeTree,deep,isUndef} from '../../shared/util'
import Evt from 'ph-evt'
import ChildTree from './tree-node.vue'
import {PhFlex} from '../base'
import {TreeNode} from './struct'
export default defineComponent({
    components:{
        ChildTree,
        PhFlex
    },
    provide(){
        return {
            treeRoot:this
        }
    },
    props:{
        'return-pid':{type:Boolean},
        nodes:{type:Object},
        structured:{type:Boolean,default:true},
        checkable:{type:Boolean,default:false},
        values:{type:Array,default:()=>[]}
    },
    setup(props){
        const treeRootEvt = new Evt()
        const trees = computed<Array<TreeNode>>(()=>{
            let trees = (props.nodes instanceof Array)? props.nodes:[props.nodes];
            if(!props.structured)
                trees = makeTree(trees)
            return trees
        })
        const vs = computed(()=>{
            if(props.values.length==0)return []
            const flat:{[k:string]:TreeNode} = {}
            const trees = (props.nodes instanceof Array)? props.nodes:[props.nodes];
            deep(trees,(item:TreeNode)=>{
                flat[item.id] = item
            })
            
            const map:{[k:string]:boolean} = {};
            let vs = (props.values instanceof Array)?props.values:[props.values];
                vs = (props.checkable?vs:[vs[0]]) as string[];
            vs.forEach(a=>{
                map[a] = true
                let flag = flat[a as string].pid as string
                while(!isUndef(flag)){
                    map[flag]=true
                    flag = flat[flag as string].pid as string
                }
            })
            return Object.keys(map)
        })
        provide("treeRootEvt",treeRootEvt)
        provide("pevt",treeRootEvt)
        return {trees,vs}
    },
    methods:{
        change(){
            const ids:string[] = []
            const $refs = this.$refs as {[k:string]:{checked:boolean,getCheckededNodes:()=>Array<string>}}
            for(let k in $refs){
                if($refs[k].checked)ids.push(...$refs[k].getCheckededNodes())
            }
            this.$emit("select",ids)
        }
    }
})
</script>
<style lang="scss" scoped>
.ph-tree{
    color:var(--ph-c);
    line-height: 1.6;
    font-size:var(--phx);
}
</style>